<?php
/**
 * Created by PhpStorm.
 * User: jjj
 * Date: 2018/3/14
 * Time: 10:24
 */

namespace app\admin\command;


use app\admin\model\live\LiveChannel;
use app\api\model\live\Live;
use think\console\Command;
use think\console\Input;
use think\console\Output;
use think\Db;

class LiveChannelStatus extends Command
{
    protected function configure()
    {
        $this->setName('liveChannelStatus');
    }
    protected function execute(Input $input, Output $output)
    {
        $channels = LiveChannel::all();
        $sel = <<<SQL
SELECT exists(
  SELECT 1 FROM live WHERE live_channel_id=:ch_id AND live_date=DATE(now()) AND status=:stat
) e
SQL;
        $upd = <<<SQL
UPDATE live_channel SET status=:stat WHERE id=:id
SQL;

        foreach ($channels as $channel) {
            $re = Db::query($sel, ['ch_id'=>$channel->id, 'stat' => Live::STATUS_START]);
            $exists = $re[0]['e'] ?? false;
            $stat = $exists ? LiveChannel::STATUS_LIVE : LiveChannel::STATUS_IDLE;
            Db::execute($upd, ['id' => $channel->id, 'stat' => $stat]);
            $statName = LiveChannel::$StatusNames[$stat];
            echo "{$channel->id}-{$channel->name} 状态: {$statName}",PHP_EOL;
        }
    }
}